package com.tmlc.way.filter;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Slf4j
@Component
public class GatewayFilter implements GlobalFilter, Ordered {

    private static final int ORDER_TOP = 0;

    @Value("${token.flag:token}")
    private String tokenFlag;

    @Value("${token.check:false}")
    private Boolean check;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (check){
            List<String> strings = exchange.getRequest().getHeaders().get(tokenFlag);
            if (null == strings || strings.isEmpty()){
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }else {
                //TODO 鉴权或录入日志
                log.info("{} token request,check this",strings.get(0));
            }
        }
        return chain.filter(exchange);
    }

    /**
     * 过滤器的优先级，数值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return ORDER_TOP;
    }

}
